package com.xydtech.common;

import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.bean.WechatMsgEntity;
import com.xydtech.common.config.UrlConfig;
import com.xydtech.common.enums.ApiContant;
import com.xydtech.common.exception.ApiException;
import com.xydtech.common.token.WechatTokenUtil;
import com.xydtech.common.utils.DateUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.spring.SpringUtils;
import com.xydtech.ecard.busi.domain.EcardApiEcardBusiReservation;
import com.xydtech.system.domain.SysWechatApplet;
import com.xydtech.system.service.ISysWechatAppletService;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;

/**
 * 电子名片小程序发送模板消息服务
 */
@Component
public class EcardApiMiniProgramSendMsgService {

    protected final Logger logger = LoggerFactory.getLogger(EcardApiMiniProgramSendMsgService.class);

    @Autowired
    private ISysWechatAppletService sysWeChatAppletService;

    private static CacheManager cacheManager = SpringUtils.getBean(CacheManager.class);

    @Autowired
    private UrlConfig urlConfig;

    /**
     * 发送业务预约微信小程序消息
     */
    public void sendBusiReservationMessage(String appId, String openId, EcardApiEcardBusiReservation busiReservation, String apiServiceUrl) {

        //获取配置的小程序的appid、secret和模板内容
        SysWechatApplet sysWechatApplet = sysWeChatAppletService.getWechatAppletByAppId(ApiContant.APPLETTYPE_ECARD, appId);
        //模板ID
        String templateId = sysWechatApplet.getTemplateId();
        String minipaogramState = sysWechatApplet.getVersionDesc();
        //请求微信小程序的时候，其中的data分部的模板数据（因为申请出来的模板这块的内容是不一样的，因此进行了客制化）
        String templateDataContent = sysWechatApplet.getTemplate();

        /**
         * 组装发送内容
         */
        WechatMsgEntity wechatMsgEntity = new WechatMsgEntity();
        wechatMsgEntity.setTouser(openId);
        wechatMsgEntity.setTemplate_id(templateId);
        //设置环境
        wechatMsgEntity.setMiniprogram_state(minipaogramState);
        wechatMsgEntity.setLang("zh_CN");
        wechatMsgEntity.setPage("pages/manager/appdetail/index?resId=" + busiReservation.getResId() + "&sts=0");

        //组装客制化配置的data内容
        templateDataContent = templateDataContent.replace("cName", busiReservation.getCname());
        templateDataContent = templateDataContent.replace("phoneNumber", busiReservation.getTelNo());
        templateDataContent = templateDataContent.replace("createTime", DateUtils.getDate());
        templateDataContent = templateDataContent.replace("prdName", busiReservation.getResPrdName());

        wechatMsgEntity.setData(JSONObject.parseObject(templateDataContent));

        sendSubscribeMessage(appId, sysWechatApplet.getSecret(), (JSONObject) JSONObject.toJSON(wechatMsgEntity), apiServiceUrl);
    }

    /**
     * 发送模板消息
     * @param appId
     */
    public void sendSubscribeMessage(String appId, String secret, JSONObject msgContent, String apiServiceUrl) {
        String appleSendUrl = urlConfig.appleSendUrl;
        //获取access_token信息
        String accesstoken = WechatTokenUtil.getEcardMiniProgramAccessToken(appId, secret, appleSendUrl, apiServiceUrl);
        if (StringUtils.isEmpty(accesstoken)) {
            throw new ApiException("获取access_token失败！");
        }

        String sendSubscribeMessageUrl = appleSendUrl + "/message/subscribe/send?access_token={0}";
        sendSubscribeMessageUrl = MessageFormat.format(sendSubscribeMessageUrl, accesstoken);
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        // 以JSON的形式发送请求
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将请求头部和参数合成一个请求
        HttpEntity<JSONObject> request = new HttpEntity<>(msgContent, headers);

        ResponseEntity<String> postForEntity = restTemplate.postForEntity(sendSubscribeMessageUrl, request, String.class);
        String body = postForEntity.getBody();
        logger.info(body);
    }
}
